package com.itheima.reggie.web.filters; /**
 * ${describe}
 *
 * @Name ${NAME}
 * @Author BaiXin
 * @Date 2022-10-30 9:01
 */

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.config.common.BaseContext;
import com.itheima.reggie.config.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "LoginCheckFilter")
public class LoginCheckFilter implements Filter {
    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //1获取uri
        String uri = request.getRequestURI();
        log.warn("拦截到的URI：{}", uri);
        //定义需要放行的资源
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/upload",
                "/common/download",
                "/user/sendMsg",
                "/user/login"

        };
        //2.判断是否是需要放行的资源
        boolean flag = matchUrl(uri, urls);
        if (flag) {
            log.info("本次请求{}不处理", uri);
            chain.doFilter(request, response);
            return;
        }
        //不是，判断用户是否登录
        Long employeeId = (Long) request.getSession().getAttribute("employee");
        if (null != employeeId) {
            //登录，放行
            BaseContext.setThreadLocal(employeeId);
            chain.doFilter(request, response);
            return;
        }
        Long userId = (Long) request.getSession().getAttribute("userId");
        if (null != userId) {
            //登录，放行
            BaseContext.setThreadLocal(userId);
            chain.doFilter(request, response);
            return;
        }
        //未登录，跳转
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }


    /**
     * 路径匹配，检查本次请求是否需要放行
     *
     * @param urls
     * @param uri
     * @return
     */
    public boolean matchUrl(String uri, String[] urls) {
        for (String url : urls) {
            boolean flag = ANT_PATH_MATCHER.match(url, uri);
            if (flag) {
                return true;
            }
        }
        return false;
    }
}
